package com.id.supaclean.ui

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.id.supaclean.MyApplication.Companion.appContext
import com.id.supaclean.R
import com.id.supaclean.ktx.repeatOnLifecycle
import com.id.supaclean.utils.Events
import com.id.supaclean.widget.SubSku
import com.id.supaclean.widget.UserCanceledPayException
import com.id.supaclean.widget.pay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class RetainFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_retain, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.findViewById<ImageView>(R.id.continue_btn).setOnClickListener {
            purchaseTrail()
        }
        view.findViewById<ImageView>(R.id.trail_btn).setOnClickListener {
            purchaseTrail()
        }
        view.findViewById<ConstraintLayout>(R.id.retainFragment_bg).setOnClickListener {
            this.requireActivity().onBackPressed()
        }

    }

    fun purchaseTrail() {
        lifecycleScope.launch {
            Events.sendEvent("canceled_paywall_continue${SubSku.SkuTrail.skuId}")
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                this@RetainFragment.requireActivity().pay(SubSku.SkuTrail).catch { e ->
                    if (e !is UserCanceledPayException) {
                        Events.sendEvent(
                            "canceled_paywall_sku_fail_${SubSku.SkuTrail.skuId}",
                            "reason" to e.message
                        )
                        Toast.makeText(
                            this@RetainFragment.requireActivity(),
                            "Network Error",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }.collectLatest {
                    Events.sendEvent("canceled_paywall_sku_success_${SubSku.SkuTrail.skuId}")
                }
            }
        }
    }

}